package com.tebiecloud.mpweixin.server.controller;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.tebiecloud.ali.client.constants.SmsTypeEnum;
import com.tebiecloud.base.client.constants.BaseConstants;
import com.tebiecloud.common.security.SecurityHelper;
import com.tebiecloud.common.security.SecurityUserDetails;
import com.tebiecloud.common.utils.*;
import com.tebiecloud.mpweixin.client.constants.MpweixinConstants;
import com.tebiecloud.mpweixin.client.constants.ResultEnum;
import com.tebiecloud.mpweixin.client.model.entity.MpweixinUserExpand;
import com.tebiecloud.mpweixin.client.model.vo.PersonalInfoVO;
import com.tebiecloud.mpweixin.client.model.vo.RightsVO;
import com.tebiecloud.mpweixin.server.service.MpweixinUserExpandService;
import com.tebiecloud.common.model.ResultBody;
import com.tebiecloud.mpweixin.server.service.feign.AliSmsServiceClient;
import com.tebiecloud.mpweixin.server.service.feign.OrderGoodsServiceClient;
import com.tebiecloud.order.client.model.entity.OrderGoods;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;

/**
 * 用户拓展表 前端控制器
 * @author tebie
 * @date 2019-09-16
 */
@Slf4j
@RestController
@RequestMapping("/mpweixinuserexpand")
public class MpweixinUserExpandController {

    @Autowired
    private MpweixinUserExpandService mpweixinUserExpandService;

    @Autowired
    private AliSmsServiceClient aliSmsServiceClient;

    @Autowired
    private OrderGoodsServiceClient orderGoodsServiceClient;

    @Autowired
    private RedisUtils redisUtils;

    /**
     * 发送换绑手机验证码
     * @return
     */
    @PostMapping("phone/sendcode")
    public ResultBody sendcode(@RequestParam(value = "phone") String phone) {
        // 获取历史发送次数
        String sendTimesStr = redisUtils.get(MpweixinConstants.REDIS_BIND_SMS_CODE_TIMES_ + phone);
        int sendTimes = DigitUtils.str2Int(sendTimesStr, 0);

        if(sendTimes >= 1) {
            log.info("xiaoc>> 请求发送验证码失败，操作过于频繁，sendTimes: {}", sendTimes);
            return ResultBodyUtils.failed("操作过于频繁，请稍后再试");
        }

        String code = RandomValueUtils.randomNumeric(6);
        ResultBody<String> retSendCode = aliSmsServiceClient.sendCode(phone, code, SmsTypeEnum.BIND_PHONE_CODE);
        if(retSendCode.getCode() != com.tebiecloud.common.constants.ResultEnum.OK.getCode()) {
            return retSendCode;
        }

        // 将验证码保存redis
        redisUtils.set(MpweixinConstants.REDIS_BIND_SMS_CODE_ + phone, code, 10 * 60);
        redisUtils.set(MpweixinConstants.REDIS_BIND_SMS_CODE_TIMES_ + phone, String.valueOf(sendTimes + 1), 60);

        log.info("xiaoc>> 已发送换绑手机验证码，code: {}", code);
        return ResultBodyUtils.ok("发送成功");
    }


    /**
     * 个人信息中心
     * @return
     */
    @PostMapping("personal/info")
    public ResultBody<PersonalInfoVO> infoPersonal() {
        //获取当前用户
        SecurityUserDetails securityUserDetails = SecurityHelper.getUser();
        String openid = "";
        if(securityUserDetails.getAccountType().equals(BaseConstants.ACCOUNT_TYPE_MP)){
            openid = securityUserDetails.getUsername().split(":")[1];
        }
        return ResultBodyUtils.ok(mpweixinUserExpandService.infoPersonal(securityUserDetails.getUserId(),openid));
    }

    /**
     * 个人信息中心
     * @return
     */
    @PostMapping("personal/infodata")
    public ResultBody<MpweixinUserExpand> information() {
        //获取当前用户
        SecurityUserDetails securityUserDetails = SecurityHelper.getUser();
        String openid = "";
        if(securityUserDetails.getAccountType().equals(BaseConstants.ACCOUNT_TYPE_MP)){
            openid = securityUserDetails.getUsername().split(":")[1];
        }
        return ResultBodyUtils.ok(mpweixinUserExpandService.information(securityUserDetails.getUserId(),openid));
    }

    /**
     * 更新数据
     * @param headimgurl 头像
     * @param nickname 昵称
     * @param sex 用户的性别，值为1时是男性，值为2时是女性，值为0时是未知
     * @param birthday 生日
     * @return
     */
    @PostMapping("update")
    public ResultBody update(
            @RequestParam(value = "headimgurl", required = false) String headimgurl,
            @RequestParam(value = "nickname", required = false) String nickname,
            @RequestParam(value = "phone", required = false) String phone,
            @RequestParam(value = "sex", required = false) Integer sex,
            @RequestParam(value = "birthday", required = false) Date birthday,
            @RequestParam(value = "code", required = false) String code
    ) {
        if(StringUtils.isNotEmpty(phone)){//如果手机号不为空，则校验
            if(StringUtils.isNotEmpty(code)){
                return ResultBodyUtils.failed(ResultEnum.PHONE_CODE_NOT_NULL.getMessage());
            }
            //校验手机号和验证码是否一致
            String codeOld = redisUtils.get(MpweixinConstants.REDIS_BIND_SMS_CODE_ + phone);
            if(org.apache.commons.lang3.StringUtils.isEmpty(codeOld) || !codeOld.equalsIgnoreCase(code)) {
                return ResultBodyUtils.failed("验证码有误");
            }
        }
        SecurityUserDetails securityUserDetails = SecurityHelper.getUser();
        if(securityUserDetails!=null && securityUserDetails.getUserId()!=null){
            UpdateWrapper<MpweixinUserExpand> mpweixinUserExpandUpdateWrapper = new UpdateWrapper<MpweixinUserExpand>();
            mpweixinUserExpandUpdateWrapper.eq("user_id",securityUserDetails.getUserId());
            MpweixinUserExpand entity = new MpweixinUserExpand();
            entity.setHeadimgurl(headimgurl);
            entity.setNickname(nickname);
            entity.setSex(sex);
            entity.setPhone(phone);
            entity.setBirthday(birthday);
            mpweixinUserExpandService.update(entity,mpweixinUserExpandUpdateWrapper);
            return ResultBodyUtils.ok();
        }else{
            return ResultBodyUtils.failed(ResultEnum.USER_NOT_ACCESS.getMessage());
        }

    }

    /**
     * 权益信息
     * @return
     */
    @PostMapping("inforights")
    public ResultBody<RightsVO> inforights() {
        RightsVO rightsVO = new RightsVO();
        //获取当前用户
        SecurityUserDetails securityUserDetails = SecurityHelper.getUser();
        String openid = "";
        if(securityUserDetails.getAccountType().equals(BaseConstants.ACCOUNT_TYPE_MP)){
            openid = securityUserDetails.getUsername().split(":")[1];
        }
        MpweixinUserExpand mpweixinUserExpand = mpweixinUserExpandService.createOrFind(securityUserDetails.getUserId(),openid);
        if(mpweixinUserExpand!=null){
            BeanUtils.copyProperties(mpweixinUserExpand,rightsVO);
            //tebie_ 指定头部，校验是否是本系统的
            String writeOffCode = "tebie_"+UUIDUtil.get32UUID();
            //将新的核销码添加到redis
            redisUtils.set(MpweixinConstants.REDIS_WRITE_OFF_+writeOffCode, securityUserDetails.getUserId().toString(), 2 * 60);
            rightsVO.setWriteOffCode(writeOffCode);
            //查询权益有多少
            ResultBody<List<OrderGoods>> listResultBody = orderGoodsServiceClient.selectOrderGoods(securityUserDetails.getUserId());
            if(listResultBody!=null && listResultBody.getCode() == com.tebiecloud.common.constants.ResultEnum.OK.getCode()){
                List<OrderGoods> orderGoodsList = listResultBody.getData();
                int rightsNumber = 0;
                for(OrderGoods orderGoods:orderGoodsList){
                    rightsNumber = rightsNumber + orderGoods.getRemainWriteOffTimes();
                }
                rightsVO.setRightsNumber(rightsNumber);
            }
        }
        return ResultBodyUtils.ok(rightsVO);
    }

}
